package com.handtransaction.controller;

import com.handtransaction.entity.Category;
import com.handtransaction.entity.Goods;
import com.handtransaction.entity.User;
import com.handtransaction.service.CategoryService;
import com.handtransaction.service.GoodsService;
import com.handtransaction.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author YAO
 * @create 2021-04-01 0:31
 */
@Controller
public class GoodsController {

    @Autowired
    GoodsService goodsService;

    @Autowired
    UserService userService;



    /**
     * @param goods        要添加的商品
     * @param modelAndView
     * @param model
     * @param uid          上传商品的用户id
     * @param file         上传商品的图片文件
     * @param request
     * @param response
     * @return 处理用户上传商品的方法
     */
    @RequestMapping(value = "addGoods", method = RequestMethod.POST)
    public ModelAndView addGoods(Goods goods, ModelAndView modelAndView, Model model
            , @RequestParam(value = "guid", required = true) int uid, @RequestParam(value = "gimgfile", required = false) MultipartFile file
            , HttpServletRequest request, HttpServletResponse response) {
//        -----------------------------------------
//        处理商品图片的上传
        //保存到数据库的路径
        String sqlPath = null;
        if (!file.isEmpty()) {    //如果上传了图片
            try {
                String path = request.getServletContext().getRealPath("/imgs/goodimg");
                String fileName = file.getOriginalFilename();
                File f = new File(path, fileName);
                if (!f.exists()) {
                    f.mkdirs();
                    System.out.println(f);
                }
                file.transferTo(f);
//                File.separator
                //把图片的相对路径保存至数据库
                sqlPath = "imgs/goodimg/" + fileName;
                goods.setGimg_path(sqlPath);
                request.getSession().setAttribute("gimg_path", sqlPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        ------------------------------------------------------------
        User user = userService.QueryUserByuid(uid);
        model.addAttribute("user", user);
//        goodsService.AddGoods(goods);
        goodsService.AddGoods2(goods);
        modelAndView.setViewName("common/succ");
        return modelAndView;
    }

    /**
     * 处理用户编辑商品
     *
     * @param goods
     * @param modelAndView
     * @param model
     * @param uid
     * @param file
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "updateGoods", method = RequestMethod.POST)
    public ModelAndView updateGoods(Goods goods, ModelAndView modelAndView, Model model
            , @RequestParam(value = "uid", required = false) Integer uid,
                                    @RequestParam(value = "imgfile", required = false) MultipartFile file
            , HttpServletRequest request, HttpServletResponse response) {
        // 处理商品图片的上传
        String sqlPath = null; //保存到数据库的路径
        if (!file.isEmpty()){
            try {
                String path = request.getServletContext().getRealPath("/imgs/goodimg");
                String fileName = file.getOriginalFilename();
                File f = new File(path, fileName);
                if (!f.exists()) {
                    f.mkdirs();
                    System.out.println(f);
                }
                file.transferTo(f);
                //把图片的相对路径保存至数据库
                sqlPath = "imgs/goodimg/" + fileName;
                goods.setGimg_path(sqlPath);
                request.getSession().setAttribute("gimg_path", sqlPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        User user = userService.QueryUserByuid(uid);
        model.addAttribute("user", user);
        goodsService.updateGoods(goods);
        modelAndView.setViewName("common/succ");
        return modelAndView;
    }

    /**
     * 主页显示所有商品信息
     * @param model
     * @param modelAndView
     * @param request
     * @param response
     * @return
     * @throws NoSuchMethodException
     */
    @RequestMapping(value = "ShowALLGoods", method = RequestMethod.GET)
    public String testGoods(Model model, ModelAndView modelAndView,
                            HttpServletRequest request, HttpServletResponse response
    ) throws NoSuchMethodException {
//        获取所有商品信息，存储在list中
        List<Goods> list = goodsService.QueryGoods();
        model.addAttribute("goodslist", list);
//        List<Category> cate=categoryService.queryAllCategory();
//        model.addAttribute("categorylist",cate);
//        modelAndView.addObject("goodslist",list);
//        request.getSession().setAttribute("goodslist",list);
//        request.setAttribute("goodslist",list);

//        ------------------------------------------------------

//        反射的小尝试，可忽略
        /*
        判断登录了
    if(request.getSession().getAttribute("user")!=null){
        Class<User> clazz = User.class;
        Method method = request.getSession().getAttribute("user").getClass().getMethod("getUimg_path");
//        Method method = clazz.getMethod("getUimg_path");
//       Object obj = method.invoke(obj);
        System.out.println(method);
        System.out.println("1");
    }*/
//--------------------------------------------------------------------------------
        return "common/showAllGoods";
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView showAllGoods(Model model, ModelAndView modelAndView) {
        List<Goods> list = goodsService.QueryGoods();
//        model.addAttribute("goodslist",list);
        modelAndView.addObject("goodslist", list);
        modelAndView.setViewName("common/showAllGoods");
        return modelAndView;
    }

    /**
     * 显示单个商品详细信息
     *
     * @param modelAndView
     * @param gid          商品的id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "getSingleGood", method = RequestMethod.GET)
    public ModelAndView getSingleGood(
            ModelAndView modelAndView,
            @RequestParam(value = "gid", required = true) int gid
            , @RequestParam(value = "uid", required = false) Integer uid,
            HttpServletRequest request, HttpServletResponse response) {
        Goods goods = goodsService.QueryGoodBygid(gid);
        modelAndView.addObject("goods", goods);
//        request.getSession().setAttribute("good", goods);
        User user = userService.QueryUserByuid(uid);
        modelAndView.addObject("user", user);
        modelAndView.setViewName("goods/detail");
        return modelAndView;
    }

    /**
     * 处理商品搜索功能
     *
     * @param modelAndView
     * @param gmessage     搜索的内容
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "showGoodsSearchResult", method = RequestMethod.POST)
    public ModelAndView showGoodsSearchResult(
            ModelAndView modelAndView,
            @RequestParam(value = "gmessage", required = true) String gmessage,
            HttpServletRequest request, HttpServletResponse response) {
        List<Goods> goods = goodsService.QueryGoodBygm(gmessage);
        modelAndView.addObject("gmessage", gmessage);
        modelAndView.addObject("goodsresult", goods);
        modelAndView.setViewName("goods/showGoodsSearchResult");
        request.getSession().setAttribute("goodsresult", goods);
        return modelAndView;
    }

    @RequestMapping(value = "showGoodsBygcid", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> showGoodsBygcid(
            @RequestParam(value = "gcid", required = true) String gcid

    ) throws Exception {
        List<Goods> goodsbygcid = goodsService.QueryGoodBygcid(gcid);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("goodsbygcid", goodsbygcid);
        return map;
    }

    @RequestMapping(value="showGoodsSearchResult1",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> showGoodsSearchResult1(
            @RequestParam(value = "gmessage",required = true)String gmessage
    ){
        List<Goods> goods = goodsService.QueryGoodBygm(gmessage);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("goodsresult", goods);
        return map;
    }


}
